package com.mmall.util;

import com.google.common.cache.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CacheUtil {

    private static final Logger log = LoggerFactory.getLogger(CacheUtil.class);
    private static final String STR_NULL = "null";
    private static LoadingCache< String, String> loadingCache = CacheBuilder.newBuilder()
            // 设置并发级别为8 ，并发级别是指可以同时写缓存的线程数
            .concurrencyLevel(8)
            // 设置写缓存后12小时过期
            .expireAfterWrite(12, TimeUnit.HOURS)
            // 缓存容器的初始容量
            .initialCapacity(100)
            // 缓存容器的最大容量，超过则会安装LRU算法，删除最近使用最少的数据
            .maximumSize(1000)
            // 设置要统计缓存命中率
            .recordStats()
            // 设置缓存的移除通知
            .removalListener(new RemovalListener<Object, Object>() {
                @Override
                public void onRemoval(RemovalNotification<Object, Object> removalNotification) {
                    log.debug(" LoadingCache Remove Cahe key{} , value:{} .",removalNotification.getKey(),removalNotification.getValue());
                }
            })
            // /build方法中可以指定CacheLoader，在缓存不存在时通过CacheLoader的实现自动加载缓存
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String key) throws Exception {
                    log.debug(" LoadingCache getKey is Null  Cahe key is {}.",key);
                    return "null";
                }
            });



    public static String getLoadCache(String key){
        if(StringUtils.isBlank(key)){
            return null;
        }
        String val = null;
        try {
            val = loadingCache.get(key);
            if(STR_NULL.equals(val)){
                return null;
            }
        } catch (ExecutionException e) {
            log.debug(" loadingCache 获取value 错误，key {} ，e {} ",key,e);
        }
        return val;
    }
    public static String getLoadCache(String key, String def){
        if(StringUtils.isBlank(key)){
            return def;
        }
        String val = def;
        try {
            val = loadingCache.get(key);
            if(STR_NULL.equals(val)){
                return def;
            }
        } catch (ExecutionException e) {
            log.debug(" loadingCache 获取value 错误，key {} ，e {} ",key,e);
        }
        return val;
    }

    public static void setLoadCache(String key, String val){
        if(StringUtils.isBlank(key)){
            return ;
        }
        loadingCache.put(key,val);
    }









    public static void main(String[] args) throws ExecutionException, InterruptedException {
        loadingCache.put("wanghao","wanghao");
        log.debug("wanghao");
        log.error("wanghaoerror");
        int i = 1;
        while (true){
            System.out.println(loadingCache.get("wanghao") + "     "+ i );
            Thread.sleep(1000);
            TimeUnit.SECONDS.sleep(1);
            System.out.println(loadingCache.stats().toString());
            i++;
        }



    }
}
